﻿using System.Collections.Generic;
using System.Xml.Linq;
using Boco.Digg.Domain;
using Boco.Digg.Service;

namespace Boco.Digg.Service
{
	public class StoryService : IStoryService
	{
		private IDiggGateway _gateway;
		private IMethodFactory _methodFactory;

		public StoryService(IDiggGateway gateway, IMethodFactory methodFactory)
		{
			_gateway = gateway;
			_methodFactory = methodFactory;
		}

		public IList<IStory> GetUpcomingStories(int count)
		{
			IStoryMethod method = _methodFactory.CreateStoryMethod();

			method.Status<Upcoming>().With.Count(count);

			return ExecuteStoryMethod(method);
		}

		public IList<IStory> GetStories(int count)
		{
			IStoryMethod method = _methodFactory.CreateStoryMethod();
			method.Status<All>().With.Count(count);

			return ExecuteStoryMethod(method);
		}

		public IList<IStory> GetStoriesByTopic(string topicName, int count)
		{
			IStoryMethod method = _methodFactory.CreateStoryMethod();
			method.Status<All>().In.Topic(topicName).With.Count(count);
			return ExecuteStoryMethod(method);
		}

		public IList<IStory> GetTopStories(int count)
		{
			IStoryMethod method = _methodFactory.CreateStoryMethod();
			method.Status<Top>().With.Count(count);
			return ExecuteStoryMethod(method);
		}

		private IList<IStory> ExecuteStoryMethod(IStoryMethod method)
		{
			XDocument doc = _gateway.ExecuteMethod(method);
			IList<IStory> stories = new List<IStory>();

			foreach (XElement element in doc.Descendants("story"))
			{
				IStory story = Story.Create(element);
				stories.Add(story);
			}

			return stories;
		}
	}
}